import React, { useState, useEffect } from 'react';
import './PollMessage.css';

interface PollMessageProps {
  message: {
    _id: string;
    pollData?: {
      question: string;
      options: Array<{
        text: string;
        votes: string[];
      }>;
      allowMultiple: boolean;
      expiresAt?: string;
      isExpired: boolean;
    };
    from:
      | string
      | {
          _id: string;
          username: string;
          image: string;
        };
    time: string | Date;
  };
  currentUserId: string;
  onVote: (messageId: string, optionIndex: number) => void;
}

const PollMessage: React.FC<PollMessageProps> = ({
  message,
  currentUserId,
  onVote,
}) => {
  const [pollResult, setPollResult] = useState<any>(null);
  const [isExpired, setIsExpired] = useState(false);

  useEffect(() => {
    if (!message.pollData) return;

    // 检查投票是否过期
    if (message.pollData.expiresAt) {
      const expiresAt = new Date(message.pollData.expiresAt);
      const now = new Date();
      if (now > expiresAt) {
        setIsExpired(true);
      }
    }

    // 计算投票结果
    calculatePollResult();
  }, [message]);

  const calculatePollResult = () => {
    if (!message.pollData) return;

    // 检查 pollData.options 是否存在且为数组
    if (!message.pollData.options || !Array.isArray(message.pollData.options)) {
      console.warn(
        'PollData options is not available or not an array:',
        message.pollData
      );
      return;
    }

    const totalVotes = message.pollData.options.reduce((sum, option) => {
      // 确保 option 存在且有 votes 属性
      if (!option || !Array.isArray(option.votes)) {
        return sum;
      }
      return sum + option.votes.length;
    }, 0);

    const result = {
      question: message.pollData.question || '投票问题',
      options: message.pollData.options.map(option => ({
        text: option.text || '选项',
        votes: Array.isArray(option.votes) ? option.votes.length : 0,
        percentage:
          totalVotes > 0
            ? Math.round(
                ((Array.isArray(option.votes) ? option.votes.length : 0) /
                  totalVotes) *
                  100
              )
            : 0,
        voters: Array.isArray(option.votes) ? option.votes : [],
      })),
      totalVotes,
      allowMultiple: message.pollData.allowMultiple || false,
    };

    setPollResult(result);
  };

  const handleVote = (optionIndex: number) => {
    if (
      !message.pollData ||
      !message.pollData.options ||
      !Array.isArray(message.pollData.options)
    )
      return;

    if (isExpired || message.pollData.isExpired) {
      alert('投票已过期');
      return;
    }

    // 检查是否已经投票
    const hasVoted = message.pollData.options.some(
      option =>
        option &&
        Array.isArray(option.votes) &&
        option.votes.includes(currentUserId)
    );

    if (hasVoted && !message.pollData.allowMultiple) {
      alert('您已经投过票了');
      return;
    }

    onVote(message._id, optionIndex);
  };

  const hasUserVoted = (optionIndex: number) => {
    if (
      !message.pollData ||
      !message.pollData.options ||
      !Array.isArray(message.pollData.options)
    )
      return false;
    const option = message.pollData.options[optionIndex];
    return (
      option &&
      Array.isArray(option.votes) &&
      option.votes.includes(currentUserId)
    );
  };

  const getUserVotedOptions = () => {
    if (
      !message.pollData ||
      !message.pollData.options ||
      !Array.isArray(message.pollData.options)
    )
      return [];
    const votedOptions: number[] = [];
    message.pollData.options.forEach((option, index) => {
      if (
        option &&
        Array.isArray(option.votes) &&
        option.votes.includes(currentUserId)
      ) {
        votedOptions.push(index);
      }
    });
    return votedOptions;
  };

  if (!pollResult) return null;

  return (
    <div className="poll-message">
      <div className="poll-header">
        <div className="poll-creator">
          <img
            src={
              typeof message.from === 'string'
                ? '/default-avatar.png'
                : message.from.image || '/default-avatar.png'
            }
            alt={
              typeof message.from === 'string'
                ? message.from
                : message.from.username
            }
            className="creator-avatar"
          />
          <span className="creator-name">
            {typeof message.from === 'string'
              ? message.from
              : message.from.username}
          </span>
        </div>
        <div className="poll-time">
          {new Date(message.time).toLocaleString()}
        </div>
      </div>

      <div className="poll-question">
        <h4>{pollResult.question}</h4>
        {message.pollData?.expiresAt && (
          <div className="poll-expiry">
            截止时间: {new Date(message.pollData.expiresAt).toLocaleString()}
          </div>
        )}
      </div>

      <div className="poll-options">
        {pollResult.options.map((option: any, index: number) => (
          <div
            key={index}
            className={`poll-option ${hasUserVoted(index) ? 'voted' : ''} ${isExpired ? 'expired' : ''}`}
            onClick={() =>
              !isExpired && !message.pollData?.isExpired && handleVote(index)
            }
          >
            <div className="option-content">
              <div className="option-text">{option.text}</div>
              <div className="option-stats">
                <span className="vote-count">{option.votes}票</span>
                <span className="vote-percentage">{option.percentage}%</span>
              </div>
            </div>
            <div className="vote-bar">
              <div
                className="vote-progress"
                style={{ width: `${option.percentage}%` }}
              ></div>
            </div>
          </div>
        ))}
      </div>

      <div className="poll-footer">
        <div className="poll-info">
          <span>总投票数: {pollResult.totalVotes}</span>
          {message.pollData?.allowMultiple && <span>• 多选</span>}
          {isExpired && <span>• 已过期</span>}
        </div>

        {getUserVotedOptions().length > 0 && (
          <div className="user-votes">
            您的选择:{' '}
            {getUserVotedOptions()
              .map(index => pollResult.options[index].text)
              .join(', ')}
          </div>
        )}
      </div>
    </div>
  );
};

export default PollMessage;
